// pages/shoppingCart/index.js
const app = getApp();
Page({
  data: {
    serverHost: app.config.serverHost,
    goodsList: '',
    token: '',
    result: [], // 选中的值
    checked: false, // 全选为true
    price: 0, // 总价单位为分
    serverHost: app.config.serverHost,
    off:false,
    offlist:[],
    onlist:[],
  },
  login() {
    wx.navigateTo({
      url: '../my/loging/index',
    })
  },
  onLoad(){
   this.setData({
     token: wx.getStorageSync('token') || ''
   })
  },
  // 点击删除按钮删除对应数据
  clear(){
    let _this = this
    let result = _this.data.result
    if(_this.data.result.length == 0){
      wx.showToast({
        title: '请选中要删除的商品',
        icon:'none',
        duration: 1500
      });
    }else{
      wx.showModal({
        title: '提示',
        content: '是否要删除已选中的商品',
        showCancel: true,
        cancelColor: '#000000',
        confirmColor: '#3CC51F',
        success: (a) => {
          if(a.confirm){
            var shopping_cart = wx.getStorageSync('shopping_cart')
            let temp = _this.data.goodsList.filter((e,index)=>{
              return !result.includes(index.toString())
            })
            var b = []
            _this.data.goodsList.filter((e, index) => {
              if(result.includes(index.toString())){
                b.push(e._id)
                app.globalData.goodslist.filter(a=>{
                  if(a._id == e._id){
                    a.value = 0
                  }
                })
              }
            })
            app.globalData.goodslist.filter(e => {
              if(b.includes(e._id)){
                e.value=0
              }
            })
            let temp2 = shopping_cart.filter(e => {
              return !b.includes(e.goods)
            })
            wx.setStorageSync('shopping_cart', temp2)
            _this.setData({
              goodsList: temp,
              result:[],
              checked:false,
              price: 0
            })
          }
        }
      });
    } 
  },
  // 返回首页
  toMain() {
    wx.switchTab({
      url: '../index/index',
    })
  },
  // 加值
  plus(e){
    let id = e.target.dataset.id
    let index = e.target.dataset.index
    let value = e.target.dataset.value + 1
    let temp = 'goodsList[' + index + '].value'
    let shopping_cart = wx.getStorageSync('shopping_cart')
    let a = shopping_cart.findIndex(item => {
      return item.goods == id
    })
    a >= 0 ? shopping_cart.splice(a, 1, { goods: id, value: shopping_cart[a].value + 1 }) : ''
    wx.setStorageSync('shopping_cart', shopping_cart)
    this.setData({
      [temp] :value
    })
  },
  // 减值
  minus(e){
    let id = e.target.dataset.id
    let index = e.target.dataset.index
    let value = e.target.dataset.value - 1
    let temp = 'goodsList[' + index + '].value'
    var shopping_cart = wx.getStorageSync('shopping_cart')
    var a = shopping_cart.findIndex(item => {
      return item.goods == id
    })
    a >= 0 ? shopping_cart.splice(a, 1, { goods: id, value: shopping_cart[a].value - 1 }) : ''
    wx.setStorageSync('shopping_cart', shopping_cart)
    this.setData({
      [temp] :value
    })
  },
  // 改变值
  changeValue(){
    this.changePrice()
  },
  // 单选按钮
  onChange(e) {
    let _this = this
    this.setData({
      result: e.detail
    });
      this.setData({
        checked: _this.data.result.length == _this.data.goodsList.length ? true :false
      });
      this.changePrice()
  },
  // 全选按钮
  allToggle(){
    let _this = this
    _this.setData({
      checked: !_this.data.checked
    })
    var l = _this.data.goodsList.length;
    if(_this.data.checked){
      for (var i=0;i<l;i++){
        _this.data.result.push(`${i}`)
      }
      _this.setData({
        result: _this.data.result
      })
    }else{
      _this.setData({
        result: []
      })
    }
    _this.changePrice()
  },
  // 改变总价格
  changePrice(){
    let _this = this
    let result = _this.data.result  //获取选中的值
    let price = 0 // 临时总价
    _this.data.goodsList.filter((item,index) => {
      return result.includes(index.toString())
    })
    .filter((e) => {
      return price += parseFloat(e.price) * parseInt(e.value)
    })
    _this.setData({
      price : price * 100
    })
  },
  // 跳转到商品详情页面
  toDetail(e){
    let id = e.currentTarget.dataset.id
    wx.navigateTo({
      url: '/pages/goodsDetail/goods?id=' + id
    })
  },
  // 提交订单
  onClickButton:function(){
    var _this =this;
    if (_this.data.result.length == 0){
      wx.showToast({
        title: '请选择商品',
        icon: 'none',
        duration: 1500
      })
    }else{
      let result = _this.data.result // 获取选中的值
      let id = []  // 选中的临时_id和value
      let datas = [] //跳转页面的id数组
      let price = _this.data.price/100 // 总价
      var onlist = []
      _this.data.goodsList.filter((item,index)=>{
        return result.includes(index.toString())
      })
      .filter((item)=>{
        return id.push({id:item._id,value:item.value})
      })
      console.log(id)
      new Promise((resolve, reject) => {
    
        app.api.post('web/goodslistnumber', id, (res) => {
          console.log(res.data)
          res.data.forEach(function (item, index) {
            console.log(item);
            console.log(item.number)
            console.log(id)
            var jsdata = (id)
            console.log(index)
            console.log(jsdata[index])
            if (item.number - jsdata[index].value < 0) {
              _this.setData({
                off: true
              })
              
              _this.data.offlist.push(item.name)
            }else{
              datas.push(jsdata[index])
              onlist.push(item)
            }
          })
          resolve(onlist)
        })
      })
        .then(data => {

if(_this.data.off){
  wx.showModal({
    title: '缺货提示',
    content: _this.data.offlist +"缺货"+"\n"+"若进行购买，请点击确定",
    success: function (res) {
      if (res.confirm) {
        console.log(data)
        if (data.length==0){
          wx.showToast({
            title: '请选择有货的商品',
            icon: 'none',
            duration: 1500
          })
        }else{
          var ids = JSON.stringify(data)
          datas = JSON.stringify(datas)
          wx.navigateTo({
            url: '/pages/order/payment/index?ids=' + ids + '&price=' + price + '&id=' + datas
          });
          _this.setData({
            off: false,
            offlist: []
          })
        }
      
      
      } else {
        console.log('点击取消回调')
        _this.setData({
          off: false,
          offlist:[]
        })
      }
    }
  })
}else{
  _this.setData({
    off: false,
  })
 var ids = JSON.stringify(data)
  datas = JSON.stringify(datas)
 console.log(ids);
  wx.navigateTo({
    url: '/pages/order/payment/index?ids=' + ids + '&price=' + price + '&id=' + datas
  });
}
      
         
        })
    


  
    }
  },
  onShow: function(e){
    // if (!wx.getStorageSync('token')) {
    //   wx.showToast({
    //     title: '请登录...',
    //     image: '../../static/icons/err.png',
    //     duration: 2000,
    //     success: function (res) {
    //       wx.navigateTo({
    //         url: '../my/loging/index',
    //       })
    //     }
    //   })
    // }
    this.setData({
      token: wx.getStorageSync('token') || ''
    })
    var data = wx.getStorageSync('shopping_cart')
    var a = app.globalData.goodslist.filter(e => {
      return Object.values(data).some(key => {
        e._id == key.goods?e.value = key.value:''
        return e._id == key.goods
      })
    })
    this.setData({ goodsList: a, result: [], price:0})
    this.data.goodsList.length == this.data.result.length ? this.setData({checked:true}) : this.setData({checked:false})
  },
  onHide() {
    if (!wx.getStorageSync('token')) {
      return
    }
    const model = {
      token: wx.getStorageSync('token'),
      shopping_cart: wx.getStorageSync('shopping_cart')
    }
    app.api.updateData('web/goodscart', model, (res) => {})
  },
})